# -*- coding: utf-8 -*-

import wx
import codecs
import scintilla

class TextTab(wx.Panel):
    encoding = u"utf-8"
    lineformat = u"LF"
    filename = u""
    
    def __init__(self, parent):
        self.settings = wx.GetApp().GetSettings()
        self.lineformat = self.settings["DefaultEOLMode"]
        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.text = scintilla.scintilla(self)
        sizer.Add(self.text, -1, wx.EXPAND, -1, )
        self.SetSizer(sizer)
            
    def GetLinePos(self):
        return self.text.GetCurrentLine()
        
    def GetColPos(self):
        pos = self.text.GetCurrentPos()
        curLine = self.text.GetCurrentLine()
        if curLine == 0:
            text_left = self.text.GetTextRange(0, pos)
        else:
            text_left = self.text.GetTextRange(self.text.GetLineEndPosition(curLine - 1), pos)
        return len(text_left)
    
    def GetTextLen(self):
        pos = self.text.GetCurrentPos()
        text_left = self.text.GetTextRange(0, pos)
        return len(text_left)
        
    def GetTotalLines(self):
        return self.text.GetLineCount()

    def GetTotalChars(self):
        return self.text.GetTextLength() - self.text.GetLineCount() + 1

    def GetText(self):
        return self.text.GetText()
    
    def GetLine(self, line):
        return self.text.GetLine(line)
    
    def SetEncoding(self, toEncoding):
        buf = self.text.GetText().decode(self.encoding)
        self.text.encoder = codecs.getencoder(toEncoding)
        self.text.SetText(buf.encode(toEncoding))
        self.encoding = toEncoding
    
    def SetLineFormat(self, format):
        self.lineformat = format
        if format == u"CRLF":
            self.text.SetEOLMode(wx.stc.STC_EOL_CRLF)
        elif format == u"CR":
            self.text.SetEOLMode(wx.stc.STC_EOL_CR)
        else:
            self.text.SetEOLMode(wx.stc.STC_EOL_LF)

    def SetText(self, lines=""):
        self.text.SetText(lines.encode("utf-8"))

    def AppendText(self, line):
        self.text.AddText(line)
        self.text.Modified = False